package models

import (
	"time"

	"gorm.io/gorm"
)

type User struct {
	ID          uint           `json:"id" gorm:"primaryKey"`
	Username    string         `json:"username" gorm:"uniqueIndex;size:50;not null" binding:"required"`
	Password    string         `json:"-" gorm:"size:255;not null" binding:"required"`
	RealName    string         `json:"real_name" gorm:"size:50;not null" binding:"required"`
	Phone       string         `json:"phone" gorm:"size:20"`
	Email       string         `json:"email" gorm:"size:100"`
	Status      string         `json:"status" gorm:"type:enum('active','inactive');default:'active'"`
	LastLoginAt *time.Time     `json:"last_login_at"`
	LastLoginIP string         `json:"last_login_ip" gorm:"size:50"`
	Sign        string         `json:"sign" gorm:"size:255"`
	Gender      string         `json:"gender" gorm:"type:char(1);default:''"` // 1:男, 2:女
	Mobile      string         `json:"mobile" gorm:"size:20;default:''"`
	AvatarURL   string         `json:"avatar_url" gorm:"size:255"`
	LoginCount  int            `json:"login_count" gorm:"default:0"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	Roles       []Role         `json:"roles" gorm:"many2many:user_roles;"`
	UserRoles   []UserRole     `json:"-"`
	Permissions []string       `json:"permissions" gorm:"-"` // 不存储到数据库，仅用于模板
	Customers   []Customer     `json:"-" gorm:"foreignKey:CreatedBy"`
	Logs        []OperationLog `json:"-" gorm:"foreignKey:UserID"`
}

// TableName 指定表名
func (User) TableName() string {
	return "users"
}

func (UserRole) TableName() string {
	return "user_roles"
}

// BeforeCreate 创建前钩子
func (u *User) BeforeCreate(tx *gorm.DB) error {
	if u.Status == "" {
		u.Status = "active"
	}
	return nil
}

// HasPermission 检查用户是否有指定权限
func (u *User) HasPermission(db *gorm.DB, permission string) bool {
	var count int64
	db.Table("permissions p").
		Joins("JOIN role_permissions rp ON p.id = rp.permission_id").
		Joins("JOIN user_roles ur ON rp.role_id = ur.role_id").
		Where("ur.user_id = ? AND p.name = ?", u.ID, permission).
		Count(&count)
	return count > 0
}

// HasAnyPermission 检查用户是否有任意一个权限
func (u *User) HasAnyPermission(db *gorm.DB, permissions []string) bool {
	for _, permission := range permissions {
		if u.HasPermission(db, permission) {
			return true
		}
	}
	return false
}

// GetPermissions 获取用户所有权限
func (u *User) GetPermissions(db *gorm.DB) []Permission {
	var permissions []Permission
	db.Table("permissions p").
		Joins("JOIN role_permissions rp ON p.id = rp.permission_id").
		Joins("JOIN user_roles ur ON rp.role_id = ur.role_id").
		Where("ur.user_id = ?", u.ID).
		Find(&permissions)
	return permissions
}

// LoadPermissions 加载用户权限名称列表到Permissions字段
func (u *User) LoadPermissions(db *gorm.DB) {
	var permissionNames []string
	db.Table("permissions p").
		Joins("JOIN role_permissions rp ON p.id = rp.permission_id").
		Joins("JOIN user_roles ur ON rp.role_id = ur.role_id").
		Where("ur.user_id = ?", u.ID).
		Pluck("p.name", &permissionNames)
	u.Permissions = permissionNames
}
